package com.coda.service.impl;

import com.coda.Constant.StatusConstant;
import com.coda.common.PageResult;
import com.coda.context.BaseContext;
import com.coda.dto.PageDto;
import com.coda.entity.Purchase;
import com.coda.entity.User;
import com.coda.mapper.PurchaseMapper;
import com.coda.mapper.UserMapper;
import com.coda.service.PurchaseService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseMapper purchaseMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 添加采购单
     * @param purchase
     */
    @Override
    public void addPurchase(Purchase purchase) {
        purchase.setBuyTime(Date.valueOf(LocalDate.now()));
        purchase.setIsIn(StatusConstant.USER_STATE_NOT_PASS);
        purchaseMapper.addPurchase(purchase);
    }

    /**
     * 分页查询采购单信息
     * @return
     */
    @Override
    public PageResult getPurchasePage(PageDto pageDto, Purchase purchase) {
        PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize());
        Page<Purchase> page = purchaseMapper.getPgae(purchase);
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    /**
     * 根据id删除采购单
     * @param id
     */
    @Override
    public void deletePurchase(Long id) {
        purchaseMapper.deleteById(id);
    }

    /**
     * 根据id修改采购单
     * @param purchase
     */
    @Override
    public void updatePurchase(Purchase purchase) {
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        purchase.setBuyUser(user.getUserName());
        purchaseMapper.update(purchase);
    }
}
